<?php
gatekeeper ();
$project = get_entity ( $vars ['project_guid'] );
if ($project) {
	$project->approved = true;
	$project->state = 'open';
	// create group
	$group = new ElggGroup ();
	
	// Assume we can edit or this is a new group
	$input ["briefdescription"] = "Nhóm thực hiện đề tài" . $project->title;
	$input ["name"] = $project->title;
	if (sizeof ( $input ) > 0) {
		foreach ( $input as $shortname => $value ) {
			$group->$shortname = $value;
		}
	}
	
	// Validate create
	if (! $group->name) {
		register_error ( elgg_echo ( "groups:notitle" ) );
		
		forward ( REFERER );
	}
	
	// Set group tool options
	if (isset ( $CONFIG->group_tool_options )) {
		foreach ( $CONFIG->group_tool_options as $group_option ) {
			$group_option_toggle_name = $group_option->name . "_enable";
			
			$group_option_default_value = 'yes';
			
			$group->$group_option_toggle_name = get_input ( $group_option_toggle_name, $group_option_default_value );
		}
	}
	
	$group->membership = ACCESS_PRIVATE;
	$group->access_id = ACCESS_LOGGED_IN;
	$group->grouptype = PROJECT_GROUP;
	$group->save ();
	
	$owner = true;
	foreach ( $project->students as $student_guid ) {
		
		$student = get_user_by_username ( $student_guid );
		if ($student) {
			$student->addRelationship ( $project->guid, "doneproject" );
			
			// User register is owner
			if ($owner) {
				$owner = false;
				$group->owner_guid = $student->guid;
				join_group ( $group->guid, $student->guid );
			} else {
				join_group ( $group->guid, $student->guid );
			}
		}
	}
	
	$group->save ();
	
	$project->group_url = $group->getURL ();
	$project->group_guid = $group->getGUID();
	$group->register_group_subject = $project->container_guid;
	$group->register_project = $project->getGUID ();
	$group_subject = get_entity ( $project->container_guid );
	$group->teacher_guid = $group_subject->getOwnerGUID ();
	
	join_group ( $group->guid, $group->teacher_guid );
	
	// Invisible group support
	// @todo this requires save to be called to create the acl for the group. This
	// is an odd requirement and should be removed. Either the acl creation happens
	// in the action or the visibility moves to a plugin hook
	if (elgg_get_plugin_setting ( 'hidden_groups', 'groups' ) == 'yes') {
		$visibility = ( int ) get_input ( 'vis', '', false );
		if ($visibility != ACCESS_PUBLIC && $visibility != ACCESS_LOGGED_IN) {
			$visibility = $group->group_acl;
		}
		
		if ($group->access_id != $visibility) {
			$group->access_id = $visibility;
		}
	}
	
	$group->save ();
	elgg_set_page_owner_guid ( $group->guid );	
	
}

